package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.contast.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.handler.MessageContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Gallant
 * @create 2020-07-03 18:36
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {


    @Reference
    private OrderSettingService  orderSettingService;

    // 上传表格的方法
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            // 先将上传的文件读到一个list集合中
            List<String[]> list = POIUtils.readExcel(excelFile);//此list中的数据是每一行的数据
            // 对其进行遍历取出里边的数据封装到一个新的list集合中
            if (list != null && list.size() > 0 ){
                // 将表中的数据封装到list集合中
                List<OrderSetting> orderSettings = new ArrayList<>();
                for (String[] strings : list) {//将每一行的数据封装到一个字符数组中
                    // 将表格中的数据封装成ordersetting对象
                    OrderSetting orderSetting = new OrderSetting(new Date(strings[0]), Integer.parseInt(strings[1]));// 取出第一个数据和第二个数据封装到实体类中
                    orderSettings.add(orderSetting);
                }
                // 调用service进行添加
                orderSettingService.add(orderSettings);
            }
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    // 回显数据的方法
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){// date的形式为2020-7
        try {
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    // 设置预约人数
    @RequestMapping("/editNumberByDate")//editNumberByDate
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }

    }
}
